package com.gugee.notice.core.service;

import com.gugee.notice.core.Notice;
import com.gugee.notice.core.dto.NoticeRequest;
import com.gugee.notice.core.model.SysModule;
import com.gugee.notice.core.model.SysUser;
import com.gugee.notice.core.repository.SysModuleRepository;
import com.gugee.notice.core.repository.SysUserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class NoticeService {

    @Autowired
    SysModuleRepository sysModuleRepository;
    @Autowired
    SysUserRepository sysUserRepository;
    @Autowired
    Notice notice;

    public String sendNotice(NoticeRequest noticeRequest){
        String msg = "模块不存在";
        Optional<SysModule> moduleOptional = sysModuleRepository.findByCodeId(noticeRequest.getModuleCodeId());
        if(moduleOptional.isPresent()){
            msg = "";
            List<SysUser> users = sysUserRepository.findByModuleId(moduleOptional.get().getId());

            if(users.size() < 0){
                return "无通知的用户";
            }

            List<String> mobileList = new ArrayList<>();
            List<String> emailUser = new ArrayList<>();

            for (SysUser u : users) {
                if(u.getDingdingNotice()){
                    mobileList.add(u.getPhoneNumber());
                }
                if(u.getEmailNotice()){
                    emailUser.add(u.getEmail());
                }
            }

            if(mobileList.size() > 0){
                msg += notice.sendDingNotice(mobileList,noticeRequest.getContent());
            }

        }

        return msg;

    }

}
